package velha.connection.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
import velha.VelhaMIDlet;
import velha.game.Constantes;
import velha.game.Player;
import velha.game.Rival;
import velha.game.VelhaCanvas;

public class NETServer implements CommandListener, Runnable {

    private final Form gui = new Form("Criar jogo");
    private final Command cmdCancelar = new Command("Cancelar", Command.OK, 0);
    private boolean isCancelled = true;
    private final VelhaMIDlet midlet;

    public NETServer(VelhaMIDlet midlet) {
        this.midlet = midlet;

        this.gui.addCommand(cmdCancelar);
        this.gui.setCommandListener(this);

        this.gui.append("Preparando...\n");
    }

    public void commandAction(Command c, Displayable d) {
        if (c == cmdCancelar) {
            this.isCancelled = true;
            midlet.getDisplay().setCurrent(new NETMenu(midlet));
        }
    }

    public void showGui() {
        midlet.getDisplay().setCurrent(gui);
    }

    public void run() {
        isCancelled = false;

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Alert alerta = new Alert("Erro", "Thread interrompida: " + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            midlet.getDisplay().setCurrent(alerta);
        }

        if (isCancelled) {
            return;
        }

        try {
            ServerSocketConnection servidor = (ServerSocketConnection) Connector.open("socket://:5542");

            this.gui.append("Aguardando no endereço IP: " + '"' + servidor.getLocalAddress() + '"' + "...");

            StreamConnection conn = servidor.acceptAndOpen();

            if (isCancelled) {
                return;
            }
            
            DataOutputStream out = conn.openDataOutputStream();
            DataInputStream in = conn.openDataInputStream();

            Player jogador = new Player();

            jogador.caracter = Constantes.CARACTER_PLAYER_1;
            jogador.isPlayer1 = true;
            jogador.isPrimeiro = true;
            jogador.pontos = 0;

            Rival rival = new Rival();

            rival.caracter = Constantes.CARACTER_PLAYER_2;
            rival.id = 2;
            rival.pontos = 0;

            VelhaCanvas game = new VelhaCanvas(midlet, jogador, rival);
            game.in = in;
            game.out = out;

            game.lapis.isVisivel = true;

            midlet.getDisplay().setCurrent(game);

            game.startMessageProcessing();
        } catch (IOException ex) {
            Alert alerta = new Alert("Erro", "Problema ao conectar " + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            midlet.getDisplay().setCurrent(alerta);
        }catch(SecurityException ex){
            gui.append("Você não permitiu a conexão com a internet");
        }
    }
}
